/* Copyright (c) 2024 Huawei Technologies Co., Ltd.
openFuyao is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN 'AS IS' BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */
import { containerRouterPrefix } from '../common/constants';
import { useEffect, useState, createRef } from 'openinula';
import { QuestionCircleOutlined, PlusCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import { Form, Space, Input, Button, message, Spin, Flex, Modal } from 'antd';
import BreadCrumbCom from '../components/BreadCrumbCom';
import { useLocation, useHistory } from 'inula-router';
import CodeMirrorEditor from '@/components/CodeMirrorEditor';
import { yamlTojson } from '@/utils/common';
import '@/styles/cluster.less';
import { creatCluster } from '@/api/multiclusterApi';
import '@/styles/dark.less';
export default function EditCluster() {
  const location = useLocation();
  const history = useHistory();
  const childCodeMirrorRef = createRef(null);
  const [clusetForm] = Form.useForm();
  const type = location.state.type;
  const [messageApi, contextHolder] = message.useMessage();
  const detailInfo = location.state.detailInfo;
  const [config, SetConfig] = useState();
  const [loading, setLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish = async () => {
    await clusetForm.validateFields();
    let arr = {
      name: clusetForm.getFieldsValue().cluster_name,
      kubeconfig: config ? yamlTojson(config) : '',
      clusterlabels: {},
    };
    if (clusetForm.getFieldsValue().labelList.length > 0 && clusetForm.getFieldsValue().labelList[0].key && clusetForm.getFieldsValue().labelList[0].value) {
      clusetForm.getFieldsValue().labelList.map(item => {
        arr.clusterlabels[item.key] = item.value;
      })
    }
    setLoading(true)
    if (!arr.name || !config) {
      setLoading(false)
      messageApi.error(`请填入必填信息`);
    } else {
      try {
        await creatCluster(arr);
        setLoading(false)
        messageApi.success(`纳管集群成功${clusetForm.getFieldsValue().cluster_name}！`);
        setTimeout(() => {
          history.push(`/${containerRouterPrefix}/`);
          clusetForm.resetFields();
        }, 1000);
      } catch (error) {
        setLoading(false)
        messageApi.error(`纳管集群失败${clusetForm.getFieldsValue().cluster_name}！`);
      };
    }
  }
  const oncancelEdit = () => {
    clusetForm.resetFields();
    history.push(`/${containerRouterPrefix}/`);
  }
  const handleChangeYaml = (str) => {
    SetConfig(str)
  };

  useEffect(() => {
    clusetForm.setFieldsValue({
      labelList: detailInfo?.labelList,
    });

  }, [detailInfo?.labelList]);

  return <div className={`child_content multi_cluster_edit ${localStorage.getItem('theme') === 'dark' ? 'dark_box' : ''}`}>
    {contextHolder}
    <Flex gap="middle" vertical className='flex_content'>
      <Spin tip="部署中" spinning={loading}>
        <BreadCrumbCom items={[{ title: '集群管理', path: `/${containerRouterPrefix}/` }, { title: type, path: '/' }]} />
        <div className='cluster_edit_info'>
          <p className='title' style={{ color: localStorage.getItem('theme') === 'dark' ? '#fff' : '#333' }}>集群信息</p>
          <Form
            {...layout}
            name="clusetForm"
            form={clusetForm}
            layout="vertical"
            // onFinish={onFinish}
          >
            <Form.Item
              name='cluster_name'
              label="集群名称" rules={[
                { required: true, message: '请输入集群名称' },
                {
                  min: 1,
                  message: "请输入1到63个字符，只能包含小写英文字母、数字和中划线（-），必须以字母数字开头,以字母数字结尾",
                },
                {
                  max: 63,
                  message: "请输入1到63个字符，只能包含小写英文字母、数字和中划线（-），必须以字母数字开头,以字母数字结尾",
                },
                {
                  pattern: /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,
                  message: "请输入1到63个字符，只能包含小写英文字母、数字和中划线（-），必须以字母数字开头,以字母数字结尾",
                }
              ]}>
              <Input placeholder="请输入" style={{ width: '620px' }} autoComplete='off' />
            </Form.Item>
            <p>集群标签</p>
            <div style={{ display: 'flex', margin: '8px 0' }}><p className='form_input' style={{ width: '500px', marginRight: '15px' }}>键</p><p>值</p></div>
            <Form.List name={`labelList`} title='标签'>
              {(fields, { add, remove }, { errors }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space
                      key={key}
                      style={{
                        display: 'flex',
                      }}
                      align="baseline"
                    >
                      <Form.Item
                        {...restField}
                        name={[name, 'key']}
                      >
                        <Input placeholder="请输入" className='form_input' style={{ width: '500px', marginRight: '8px' }} />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'value']}
                      >
                        <Input placeholder="请输入" className='form_input' style={{ width: '500px' }} />
                      </Form.Item>
                      <DeleteOutlined className="common_antd_icon" onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button className="icon_btn add_label" type="link" onClick={() => add()} block icon={<PlusCircleOutlined className="primary_icon common_antd_icon" />}>
                      添加标签
                    </Button>
                    <Form.ErrorList errors={errors} />
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Form>
        </div>
        <div className='cluster_config'>
          <div className='cluster_config_top'>
            <p className='title'><span style={{ color: '#e94547', marginRight: '4px', fontSize: '12px' }}>*</span>kubeconfig配置信息</p>
            <p className='get_config' onClick={showModal}><QuestionCircleOutlined style={{ width: '16px', height: '16px', color: '#346ac4' }} />如何获取kubeconfig?</p>
          </div>
          <CodeMirrorEditor yamlData={''} changeYaml={handleChangeYaml} ref={childCodeMirrorRef} />
        </div>
        <Modal className='config_modal' getContainer={false} title="获取kubeconfig" open={isModalOpen} onCancel={handleCancel}
          footer={[
            <Button onClick={handleCancel} className='cancel_btn'>
              取消
            </Button>,
            <Button className='primary_btn' onClick={handleCancel}>
              确定
            </Button>,
          ]}>
          <p className='config_modal_text'>1.进入成员集群的某一节点上。</p>
          <p className='config_modal_text'>2.在节点上执行以下命令获取成员集群的kubeconfig信息：</p>
          <div className='config_modal_code'>
            <p>kubectl config view --raw</p>
          </div>
          <p className='config_modal_text'>3.将打印到控制台的kubefonfig信息复制，填写到成员集群的kubeconfig配置信息输入框中。</p>
        </Modal>
      </Spin>
    </Flex>
    <div className='btns'>
      <Button className='cancel_btn' onClick={oncancelEdit}>
        取消
      </Button>
      <Button className='primary_btn' onClick={onFinish}>
        确定
      </Button>
    </div>
  </div >;
}